package com.cms.exception;
import java.io.CharArrayWriter;
import java.io.PrintWriter;
import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;
public class ExceptionLog {
	private static final ExceptionLog exceptionLog = new ExceptionLog();
	private static final String exceptionIdPre = String.valueOf(new Date().getTime());
	private static final AtomicLong idSuf = new AtomicLong(0);

	public static ExceptionLog getInstance() {
		return exceptionLog;
	}

	// 璁板綍寮傚父骞惰繑鍥炲紓甯�
	public ExceptionInfo recodeException(Exception e, String user, String extDebugInfo) {
		return recodeException(e, e.getMessage(), user, extDebugInfo, null);
	}

	public ExceptionInfo recodeException(Exception e, String message, String user, String extDebugInfo, Object attachment) {
		ExceptionInfo exceptionInfo = new ExceptionInfo();
		exceptionInfo.setId(getExceptionId());
		exceptionInfo.setMessage(message);
		exceptionInfo.setStackDesc(getExceptionDesc(e));
		exceptionInfo.setExtDebugInfo(extDebugInfo);
		exceptionInfo.setDate(new Date());
		exceptionInfo.setUser(user);
		exceptionInfo.setAttachment(attachment);
		ExceptionPrint.getInstance().print(exceptionInfo);// 鎵撳嵃鏃ュ織
		return exceptionInfo;
	}

	private String getExceptionId() {
		return exceptionIdPre + "-" + idSuf.incrementAndGet();
	}

	private String getExceptionDesc(Exception e) {
		CharArrayWriter buffer = new CharArrayWriter();
		PrintWriter tmpOut = new PrintWriter(buffer);
		e.printStackTrace(tmpOut);
		tmpOut.close();
		return buffer.toString();
	}
}
